package com.stable.actor.remotedemo;

import com.stable.actor.core.ActorRef;
import com.stable.actor.core.ActorSystem;
import com.stable.actor.core.Props;
import com.stable.actor.network.NetworkClient;
import lombok.extern.slf4j.Slf4j;
/**
 * 稳定的Actor框架Demo - 远程调用示例（指定具体IP和端口）
 */
@Slf4j
public class RemoteCallDemo {

    public static void main(String[] args) throws InterruptedException {
        log.info("🚀 启动远程调用Demo...");

        // 1. 创建Actor系统
        ActorSystem system = new ActorSystem("RemoteDemoSystem");

        try {
            // 2. 初始化NetworkClient（重要！）
            NetworkClient.initialize(system);

            // 3. 创建本地服务Actor
            ActorRef orderService = system.actorOf(Props.create(OrderServiceActor.class), "order-service");
            log.info("✅ 订单服务创建: " + orderService);

            // 4. 创建远程服务引用 - 指定具体的IP和端口
            log.info("🔗 创建远程服务引用...");

            // 支付服务 - 运行在192.168.1.101:8081
            ActorRef paymentService = system.remoteActorOf("192.168.1.101", 8081, "/user/payment-service");
            log.info("   💳 支付服务: " + paymentService.path());

            // 库存服务 - 运行在192.168.1.102:8082
            ActorRef inventoryService = system.remoteActorOf("192.168.1.102", 8082, "/user/inventory-service");
            log.info("   📦 库存服务: " + inventoryService.path());

            // 通知服务 - 运行在192.168.1.103:8083
            ActorRef notificationService = system.remoteActorOf("192.168.1.103", 8083, "/user/notification-service");
            log.info("   📢 通知服务: " + notificationService.path());

            // 5. 设置远程服务到订单服务
            OrderServiceActor orderActor = (OrderServiceActor) ((ActorRef) orderService).getActor();
            orderActor.setRemoteServices(paymentService, inventoryService, notificationService);

            // 6. 模拟用户请求
            log.info("\n📦 模拟用户下单流程...");

            // 创建测试订单
            Order order = new Order("ORDER-001", "user-123", "iPhone 15", 2, 5999.0);

            // 发送订单处理请求
            orderService.tell(new CreateOrderCommand(order), ActorRef.noSender());

            Thread.sleep(2000);

            // 发送另一个订单
            Order order2 = new Order("ORDER-002", "user-456", "MacBook Pro", 1, 12999.0);
            orderService.tell(new CreateOrderCommand(order2), ActorRef.noSender());

            // 7. 运行一段时间观察远程调用
            log.info("\n⏳ 观察远程调用过程...");
            Thread.sleep(10000);

        } finally {
            // 8. 关闭系统
            log.info("\n🛑 关闭Actor系统...");
            system.terminate();
            NetworkClient.shutdown();
        }

        log.info("🎉 远程调用Demo完成!");
    }
}
